<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"
          ><i class="el-icon-arrow-left" />返回</span
        >
        <span>|</span>
        <span>添加角色</span>
      </div>
      <div class="right">吃可爱的莎莎</div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="currentActive">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="currentActive === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form
            ref="infoForm"
            class="form-box"
            :model="roleForm"
            :rules="roleRules"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="currentActive === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="tree"
                :data="item.children"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                check-strictly
                :props="{ label: 'title' }"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="currentActive === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div
                v-for="item in diabledTreeList"
                :key="item.id"
                class="tree-item"
              >
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="diabledTree"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  check-strictly
                  :highlight-current="false"
                  :props="{ label: 'title', disabled: () => true }"
                ></el-tree>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="prev" v-if="currentActive > 1">上一步</el-button>
        <el-button type="primary" @click="next" v-if="currentActive < 3"
          >下一步</el-button
        >
        <el-button type="primary" v-if="currentActive === 3" @click="confirmAdd"
          >确认添加</el-button
        >
      </div>
    </footer>
  </div>
</template>

<script>
import {
  getTreeListAPI,
  addRoleAPI,
  getRoleDetailAPI,
  updateRoleAPI,
} from "@/api/system";
export default {
  data() {
    return {
      currentActive: 1,
      roleForm: {
        roleName: "",
        remark: "",
      },
      roleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      treeList: [],
      diabledTreeList: [], // 回填显示的树列表
      permsList: [], // 存放所有选中的项
    };
  },
  mounted() {
    this.getTreeList();
    if (this.$route.query.roleId) {
      this.getDetail();
    }
  },
  methods: {
    async getDetail() {
      const roleId = this.$route.query.roleId;
      const res = await getRoleDetailAPI(roleId);
      const { perms, roleName, remark } = res.data;
      this.roleForm.roleName = roleName;
      this.roleForm.remark = remark;
      // 回填树形结构 setCheckedKeys
      this.$refs.tree.forEach((tree, index) => {
        tree.setCheckedKeys(perms[index]);
      });
    },
    async confirmAdd() {
      // 编辑
      if (this.$route.query.roleId) {
        await updateRoleAPI(this.roleForm);
      } else {
        await addRoleAPI({
          ...this.roleForm,
          perms: this.permsList,
        });
      }
      this.$message({
        type: "success",
        message: `${this.$route.query.roleId ? "编辑" : "新增"}角色成功`,
      });
      this.$router.back();
    },
    async getTreeList() {
      const res = await getTreeListAPI();
      this.treeList = res.data;
      //   在diabledTreeList中放一份数据
      //   因为数组是引用类型 再进行赋值时，赋值的是数组的引用 即这两个数组指向同一个内存
      // 解决方法：深拷贝
      this.diabledTreeList = JSON.parse(JSON.stringify(res.data));
    },
    prev() {
      if (this.currentActive === 1) return;
      this.currentActive--;
    },
    next() {
      if (this.currentActive === 3) return;
      // 在角色信息状态下做表单校验 如果校验通过 则进入下一个状态
      if (this.currentActive === 1) {
        // 在角色信息状态
        // 表单校验
        this.$refs.infoForm.validate((valid) => {
          if (valid) {
            this.currentActive++;
          }
        });
      } else if (this.currentActive === 2) {
        // 选择权限信息的状态
        // 目标：判断用户至少选择了一项
        // 思路：获取到用户选择了什么
        this.permsList = [];
        this.$refs.tree.forEach((treeInstance) => {
          const keys = treeInstance.getCheckedKeys();
          //   console.log(keys);
          this.permsList.push(keys);
        });
        if (this.permsList.flat().length === 0) {
          // 没有选中
          return this.$message({
            type: "warning",
            message: "请至少选择一项",
          });
        } else {
          this.currentActive++;
          // 回填树形结构
          this.$refs.diabledTree.forEach((treeInstance, index) => {
            treeInstance.setCheckedKeys(this.permsList[index]);
          });
        }
      }
    },
  },
};
</script>

<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info {
          font-size: 14px;
          color: #666;
          .form-item {
            margin-bottom: 20px;
          }
        }
      }
      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;
      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>